home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / multiprocessing / connection.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  14KB  |  396 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __all__ = [
  5.     'Client',
  6.     'Listener',
  7.     'Pipe']
  8. import os
  9. import sys
  10. import socket
  11. import errno
  12. import time
  13. import tempfile
  14. import itertools
  15. import _multiprocessing
  16. from multiprocessing import current_process, AuthenticationError
  17. from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug
  18. from multiprocessing.forking import duplicate, close
  19. BUFSIZE = 8192
  20. _mmap_counter = itertools.count()
  21. default_family = 'AF_INET'
  22. families = [
  23.     'AF_INET']
  24. if hasattr(socket, 'AF_UNIX'):
  25.     default_family = 'AF_UNIX'
  26.     families += [
  27.         'AF_UNIX']
  28.  
  29. if sys.platform == 'win32':
  30.     default_family = 'AF_PIPE'
  31.     families += [
  32.         'AF_PIPE']
  33.  
  34.  
  35. def arbitrary_address(family):
  36.     '''
  37.     Return an arbitrary free address for the given family
  38.     '''
  39.     if family == 'AF_INET':
  40.         return ('localhost', 0)
  41.     if family == 'AF_UNIX':
  42.         return tempfile.mktemp(prefix = 'listener-', dir = get_temp_dir())
  43.     if family == 'AF_PIPE':
  44.         return tempfile.mktemp(prefix = '\\\\.\\pipe\\pyc-%d-%d-' % (os.getpid(), _mmap_counter.next()))
  45.     raise ValueError('unrecognized family')
  46.  
  47.  
  48. def address_type(address):
  49.     """
  50.     Return the types of the address
  51.  
  52.     This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
  53.     """
  54.     if type(address) == tuple:
  55.         return 'AF_INET'
  56.     if type(address) is str and address.startswith('\\\\'):
  57.         return 'AF_PIPE'
  58.     if type(address) is str:
  59.         return 'AF_UNIX'
  60.     raise ValueError('address type of %r unrecognized' % address)
  61.  
  62.  
  63. class Listener(object):
  64.     """
  65.     Returns a listener object.
  66.  
  67.     This is a wrapper for a bound socket which is 'listening' for
  68.     connections, or for a Windows named pipe.
  69.     """
  70.     
  71.     def __init__(self, address = None, family = None, backlog = 1, authkey = None):
  72.         if not family:
  73.             if not address or address_type(address):
  74.                 pass
  75.         family = default_family
  76.         if not address:
  77.             pass
  78.         address = arbitrary_address(family)
  79.         if family == 'AF_PIPE':
  80.             self._listener = PipeListener(address, backlog)
  81.         else:
  82.             self._listener = SocketListener(address, family, backlog)
  83.         if authkey is not None and not isinstance(authkey, bytes):
  84.             raise TypeError, 'authkey should be a byte string'
  85.         not isinstance(authkey, bytes)
  86.         self._authkey = authkey
  87.  
  88.     
  89.     def accept(self):
  90.         '''
  91.         Accept a connection on the bound socket or named pipe of `self`.
  92.  
  93.         Returns a `Connection` object.
  94.         '''
  95.         c = self._listener.accept()
  96.         if self._authkey:
  97.             deliver_challenge(c, self._authkey)
  98.             answer_challenge(c, self._authkey)
  99.         
  100.         return c
  101.  
  102.     
  103.     def close(self):
  104.         '''
  105.         Close the bound socket or named pipe of `self`.
  106.         '''
  107.         return self._listener.close()
  108.  
  109.     address = property((lambda self: self._listener._address))
  110.     last_accepted = property((lambda self: self._listener._last_accepted))
  111.  
  112.  
  113. def Client(address, family = None, authkey = None):
  114.     '''
  115.     Returns a connection to the address of a `Listener`
  116.     '''
  117.     if not family:
  118.         pass
  119.     family = address_type(address)
  120.     if family == 'AF_PIPE':
  121.         c = PipeClient(address)
  122.     else:
  123.         c = SocketClient(address)
  124.     if authkey is not None and not isinstance(authkey, bytes):
  125.         raise TypeError, 'authkey should be a byte string'
  126.     not isinstance(authkey, bytes)
  127.     if authkey is not None:
  128.         answer_challenge(c, authkey)
  129.         deliver_challenge(c, authkey)
  130.     
  131.     return c
  132.  
  133. if sys.platform != 'win32':
  134.     
  135.     def Pipe(duplex = True):
  136.         '''
  137.         Returns pair of connection objects at either end of a pipe
  138.         '''
  139.         if duplex:
  140.             (s1, s2) = socket.socketpair()
  141.             c1 = _multiprocessing.Connection(os.dup(s1.fileno()))
  142.             c2 = _multiprocessing.Connection(os.dup(s2.fileno()))
  143.             s1.close()
  144.             s2.close()
  145.         else:
  146.             (fd1, fd2) = os.pipe()
  147.             c1 = _multiprocessing.Connection(fd1, writable = False)
  148.             c2 = _multiprocessing.Connection(fd2, readable = False)
  149.         return (c1, c2)
  150.  
  151. else:
  152.     from _multiprocessing import win32
  153.     
  154.     def Pipe(duplex = True):
  155.         '''
  156.         Returns pair of connection objects at either end of a pipe
  157.         '''
  158.         address = arbitrary_address('AF_PIPE')
  159.         if duplex:
  160.             openmode = win32.PIPE_ACCESS_DUPLEX
  161.             access = win32.GENERIC_READ | win32.GENERIC_WRITE
  162.             obsize = BUFSIZE
  163.             ibsize = BUFSIZE
  164.         else:
  165.             openmode = win32.PIPE_ACCESS_INBOUND
  166.             access = win32.GENERIC_WRITE
  167.             obsize = 0
  168.             ibsize = BUFSIZE
  169.         h1 = win32.CreateNamedPipe(address, openmode, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL)
  170.         h2 = win32.CreateFile(address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL)
  171.         win32.SetNamedPipeHandleState(h2, win32.PIPE_READMODE_MESSAGE, None, None)
  172.         
  173.         try:
  174.             win32.ConnectNamedPipe(h1, win32.NULL)
  175.         except WindowsError:
  176.             e = None
  177.             if e.args[0] != win32.ERROR_PIPE_CONNECTED:
  178.                 raise 
  179.             e.args[0] != win32.ERROR_PIPE_CONNECTED
  180.  
  181.         c1 = _multiprocessing.PipeConnection(h1, writable = duplex)
  182.         c2 = _multiprocessing.PipeConnection(h2, readable = duplex)
  183.         return (c1, c2)
  184.  
  185.  
  186. class SocketListener(object):
  187.     '''
  188.     Representation of a socket which is bound to an address and listening
  189.     '''
  190.     
  191.     def __init__(self, address, family, backlog = 1):
  192.         self._socket = socket.socket(getattr(socket, family))
  193.         self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  194.         self._socket.bind(address)
  195.         self._socket.listen(backlog)
  196.         self._address = self._socket.getsockname()
  197.         self._family = family
  198.         self._last_accepted = None
  199.         if family == 'AF_UNIX':
  200.             self._unlink = Finalize(self, os.unlink, args = (address,), exitpriority = 0)
  201.         else:
  202.             self._unlink = None
  203.  
  204.     
  205.     def accept(self):
  206.         (s, self._last_accepted) = self._socket.accept()
  207.         fd = duplicate(s.fileno())
  208.         conn = _multiprocessing.Connection(fd)
  209.         s.close()
  210.         return conn
  211.  
  212.     
  213.     def close(self):
  214.         self._socket.close()
  215.         if self._unlink is not None:
  216.             self._unlink()
  217.         
  218.  
  219.  
  220.  
  221. def SocketClient(address):
  222.     '''
  223.     Return a connection object connected to the socket given by `address`
  224.     '''
  225.     family = address_type(address)
  226.     s = socket.socket(getattr(socket, family))
  227.     while None:
  228.         
  229.         try:
  230.             s.connect(address)
  231.         except socket.error:
  232.             e = None
  233.             if e.args[0] != errno.ECONNREFUSED:
  234.                 debug('failed to connect to address %s', address)
  235.                 raise 
  236.             e.args[0] != errno.ECONNREFUSED
  237.             time.sleep(0.01)
  238.             continue
  239.  
  240.         break
  241.         continue
  242.         raise 
  243.         fd = duplicate(s.fileno())
  244.         conn = _multiprocessing.Connection(fd)
  245.         return conn
  246.  
  247. if sys.platform == 'win32':
  248.     
  249.     class PipeListener(object):
  250.         '''
  251.         Representation of a named pipe
  252.         '''
  253.         
  254.         def __init__(self, address, backlog = None):
  255.             self._address = address
  256.             handle = win32.CreateNamedPipe(address, win32.PIPE_ACCESS_DUPLEX, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, win32.NMPWAIT_WAIT_FOREVER, win32.NULL)
  257.             self._handle_queue = [
  258.                 handle]
  259.             self._last_accepted = None
  260.             sub_debug('listener created with address=%r', self._address)
  261.             self.close = Finalize(self, PipeListener._finalize_pipe_listener, args = (self._handle_queue, self._address), exitpriority = 0)
  262.  
  263.         
  264.         def accept(self):
  265.             newhandle = win32.CreateNamedPipe(self._address, win32.PIPE_ACCESS_DUPLEX, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, win32.NMPWAIT_WAIT_FOREVER, win32.NULL)
  266.             self._handle_queue.append(newhandle)
  267.             handle = self._handle_queue.pop(0)
  268.             
  269.             try:
  270.                 win32.ConnectNamedPipe(handle, win32.NULL)
  271.             except WindowsError:
  272.                 e = None
  273.                 if e.args[0] != win32.ERROR_PIPE_CONNECTED:
  274.                     raise 
  275.                 e.args[0] != win32.ERROR_PIPE_CONNECTED
  276.  
  277.             return _multiprocessing.PipeConnection(handle)
  278.  
  279.         
  280.         def _finalize_pipe_listener(queue, address):
  281.             sub_debug('closing listener with address=%r', address)
  282.             for handle in queue:
  283.                 close(handle)
  284.             
  285.  
  286.         _finalize_pipe_listener = staticmethod(_finalize_pipe_listener)
  287.  
  288.     
  289.     def PipeClient(address):
  290.         '''
  291.         Return a connection object connected to the pipe given by `address`
  292.         '''
  293.         while None:
  294.             
  295.             try:
  296.                 win32.WaitNamedPipe(address, 1000)
  297.                 h = win32.CreateFile(address, win32.GENERIC_READ | win32.GENERIC_WRITE, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL)
  298.             except WindowsError:
  299.                 e = None
  300.                 if e.args[0] not in (win32.ERROR_SEM_TIMEOUT, win32.ERROR_PIPE_BUSY):
  301.                     raise 
  302.                 e.args[0] not in (win32.ERROR_SEM_TIMEOUT, win32.ERROR_PIPE_BUSY)
  303.                 continue
  304.  
  305.             break
  306.             continue
  307.             raise 
  308.             return _multiprocessing.PipeConnection(h)
  309.  
  310.  
  311. MESSAGE_LENGTH = 20
  312. CHALLENGE = '#CHALLENGE#'
  313. WELCOME = '#WELCOME#'
  314. FAILURE = '#FAILURE#'
  315.  
  316. def deliver_challenge(connection, authkey):
  317.     import hmac as hmac
  318.     if not isinstance(authkey, bytes):
  319.         raise AssertionError
  320.     message = os.urandom(MESSAGE_LENGTH)
  321.     connection.send_bytes(CHALLENGE + message)
  322.     digest = hmac.new(authkey, message).digest()
  323.     response = connection.recv_bytes(256)
  324.     if response == digest:
  325.         connection.send_bytes(WELCOME)
  326.     else:
  327.         connection.send_bytes(FAILURE)
  328.         raise AuthenticationError('digest received was wrong')
  329.     return isinstance(authkey, bytes)
  330.  
  331.  
  332. def answer_challenge(connection, authkey):
  333.     import hmac
  334.     if not isinstance(authkey, bytes):
  335.         raise AssertionError
  336.     message = connection.recv_bytes(256)
  337.     if not message[:len(CHALLENGE)] == CHALLENGE:
  338.         raise AssertionError, 'message = %r' % message
  339.     message = message[len(CHALLENGE):]
  340.     digest = hmac.new(authkey, message).digest()
  341.     connection.send_bytes(digest)
  342.     response = connection.recv_bytes(256)
  343.     if response != WELCOME:
  344.         raise AuthenticationError('digest sent was rejected')
  345.     response != WELCOME
  346.  
  347.  
  348. class ConnectionWrapper(object):
  349.     
  350.     def __init__(self, conn, dumps, loads):
  351.         self._conn = conn
  352.         self._dumps = dumps
  353.         self._loads = loads
  354.         for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
  355.             obj = getattr(conn, attr)
  356.             setattr(self, attr, obj)
  357.         
  358.  
  359.     
  360.     def send(self, obj):
  361.         s = self._dumps(obj)
  362.         self._conn.send_bytes(s)
  363.  
  364.     
  365.     def recv(self):
  366.         s = self._conn.recv_bytes()
  367.         return self._loads(s)
  368.  
  369.  
  370.  
  371. def _xml_dumps(obj):
  372.     return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8')
  373.  
  374.  
  375. def _xml_loads(s):
  376.     (obj,) = ()
  377.     method = xmlrpclib.loads(s.decode('utf8'))
  378.     return obj
  379.  
  380.  
  381. class XmlListener(Listener):
  382.     
  383.     def accept(self):
  384.         global xmlrpclib
  385.         import xmlrpclib
  386.         obj = Listener.accept(self)
  387.         return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
  388.  
  389.  
  390.  
  391. def XmlClient(*args, **kwds):
  392.     global xmlrpclib
  393.     import xmlrpclib
  394.     return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
  395.  
  396.